package com.seya.calculite.app;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;


public class OutputActivity extends Activity {

    DatabaseHandler dbHandler;
    ProgressDialog pDialog;

    Context c;
    GPSTracker gps;
    SharedPreferences prefs;

    TextView txt_vehicle, txt_company, txt_start, txt_end, txt_time, txt_km, txt_tag;
    String elocation;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.activity_open_translate,R.anim.activity_close_scale);
        setContentView(R.layout.activity_output);
        FontHelper.applyFont(this, findViewById(R.id.activity_main_root), "RobotoLight.ttf");

        c = getApplicationContext();

        txt_vehicle = (TextView)findViewById(R.id.opt_vehicle);
        txt_company = (TextView)findViewById(R.id.opt_company);
        txt_start = (TextView)findViewById(R.id.opt_start);
        txt_end = (TextView)findViewById(R.id.opt_end);
        txt_time = (TextView)findViewById(R.id.opt_time);
        txt_km = (TextView)findViewById(R.id.opt_km);
        txt_tag = (TextView)findViewById(R.id.opt_tag);

        gps = new GPSTracker(OutputActivity.this);
        new GetLocation().execute();

        prefs = getApplicationContext().getSharedPreferences(SplashScreenActivity.SHARED_PREFERENCES_NAME, MODE_PRIVATE);
        txt_vehicle.setText(prefs.getString(SplashScreenActivity.VEHICLE,""));
        txt_company.setText(prefs.getString(SplashScreenActivity.COMPANY,""));
        txt_start.setText(prefs.getString(SplashScreenActivity.START_LOCATION,""));
        txt_end.setText(prefs.getString(SplashScreenActivity.END_LATITUDE,"0")+", "+prefs.getString(SplashScreenActivity.END_LONGITUDE,"0"));
        txt_time.setText(prefs.getString(SplashScreenActivity.TOTAL_TIME,"00:00:00"));
        txt_km.setText(prefs.getString(SplashScreenActivity.KILOMETER,"000"));
        txt_tag.setText(prefs.getString(SplashScreenActivity.TAG,""));
    }

    private class GetLocation extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(OutputActivity.this);
            pDialog.setMessage("Please wait...Getting Location");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            if(gps.canGetLocation()){
                try {
                    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
                    List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(prefs.getString(SplashScreenActivity.END_LATITUDE,"0")), Double.parseDouble(prefs.getString(SplashScreenActivity.END_LONGITUDE,"0")), 1);
                    if (addresses.size() > 0) {
                        elocation = addresses.get(0).getThoroughfare() + ", "+addresses.get(0).getSubLocality() + ", " +
                                addresses.get(0).getLocality() + ", "+addresses.get(0).getPostalCode();
                    }
                }
                catch (Exception e) {
                    elocation = prefs.getString(SplashScreenActivity.END_LATITUDE,"0")+", "+prefs.getString(SplashScreenActivity.END_LONGITUDE,"0");
                }
            }
            else {
                elocation = prefs.getString(SplashScreenActivity.END_LATITUDE,"0")+", "+prefs.getString(SplashScreenActivity.END_LONGITUDE,"0");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (pDialog.isShowing())
                pDialog.dismiss();
                txt_end.setText(elocation);

            prefs = c.getSharedPreferences(SplashScreenActivity.SHARED_PREFERENCES_NAME, MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(SplashScreenActivity.END_LOCATION, elocation);
            editor.commit();
            new AddToDB().execute();
        }
    }

    private class AddToDB extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(OutputActivity.this);
            pDialog.setMessage("Saving data...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            Details d = new Details(prefs.getString(SplashScreenActivity.VEHICLE,""),
                    prefs.getString(SplashScreenActivity.COMPANY,""),
                    prefs.getString(SplashScreenActivity.START_LOCATION,""),
                    prefs.getString(SplashScreenActivity.END_LOCATION,""),
                    prefs.getString(SplashScreenActivity.TOTAL_TIME,""),
                    prefs.getString(SplashScreenActivity.KILOMETER,""),
                    prefs.getString(SplashScreenActivity.TAG,""),
                    new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            dbHandler = new DatabaseHandler(OutputActivity.this);
            dbHandler.addDetails(d);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (pDialog.isShowing())
                pDialog.dismiss();
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.output, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        /*if (id == R.id.action_settings) {
            return true;
        }*/
        switch(id) {
            case R.id.action_history:
                Intent i = new Intent(OutputActivity.this, HistoryActivity.class);
                startActivity(i);
                return true;
            case R.id.action_logout:
                SharedPreferences settings = c.getSharedPreferences(SplashScreenActivity.SHARED_PREFERENCES_NAME, MODE_PRIVATE);
                settings.edit().clear().commit();
                SplashScreenActivity.loggingOut = true;
                i = new Intent(OutputActivity.this, LoginActivity.class);
                startActivity(i);
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        //closing transition animations
        overridePendingTransition(R.anim.activity_open_scale,R.anim.activity_close_translate);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(SplashScreenActivity.loggingOut){
            finish();
        }
    }
}
